package com.twang.stock.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.twang.stock.dto.TenXunStock;
import com.twang.stock.mapper.CompanyStockMinutesMapper;
import com.twang.stock.redis.RedisUtil;
import com.twang.stock.service.CompanyStockMinutesService;
import com.twang.stock.service.ZhangTingBanService;
import com.twang.stock.service.ZuoTiStrategyService;
import com.twang.stock.task.old.BaseTask;
import com.twang.stock.utils.date.HolidayCopy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

@Service
@Slf4j
public class ZuoTiStrategyServiceImpl implements ZuoTiStrategyService {

    @Resource
    private CompanyStockMinutesMapper companyStockMinutesMapper;

    @Autowired
    private CompanyStockMinutesService companyStockMinutesService;

    @Autowired
    private ZhangTingBanService zhangTingBanService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private BaseTask baseTask;

    public volatile static  String yesterDay;

    public volatile  static List<String> dates= Lists.newArrayList();

    @Override
    public TenXunStock excuteZuoTiStategy(TenXunStock p) {

        //ZT 判断是否触发量能
        extractedZuoTi(p);

        //ZT 判断现情绪是否适合做T

        //ZT

        return p;
    }

    /**
     * 判断量能是否触发
     * @param p
     */
    private void extractedZuoTi(TenXunStock p) {
        if (51 == p.getExchange()) {
            p.setStockCode("sz" + p.getStockCode());
        } else {
            p.setStockCode("sh" + p.getStockCode());
        }

        //历史平均量能
        BigDecimal historyTradeVol = getHistoryVol(p);

        String lastMinutesKey = new StringBuffer("lastMinutesKey:").append(p.getStockCode()).append(":").append(HolidayCopy.getHHmmss()).toString();
        Object lastMinutesKeyObject = redisUtil.get(lastMinutesKey);
        BigDecimal lastMinutesTradeVol;
        if (null == lastMinutesKeyObject) {
            //ZT 更新分钟量能
            lastMinutesTradeVol = companyStockMinutesMapper.queryLastStockMinutesVol(p.getStockCode(), HolidayCopy.getRealToday());
            //缓存最新的分时数据，方便下一分钟做T得到的
            redisUtil.set(lastMinutesKey, p.getTradingVolume(), 60);
            log.info(">>>>>>>>> 缓存最新的分时数据， lastMinutesKey={} ", lastMinutesKey);
        } else {
            lastMinutesTradeVol = new BigDecimal(lastMinutesKeyObject.toString());
            log.info(">>>>>>>>> 通过缓存获取到最新的数据， lastMinutesKey={}  lastMinutesTradeVol={} ", lastMinutesKey, lastMinutesTradeVol);
        }

        if (null != lastMinutesTradeVol) {
            BigDecimal newVole = p.getTradingVolume().subtract(lastMinutesTradeVol);
            if (newVole.compareTo(historyTradeVol) > 0) {
                //触发了
                p.setTFlags(1);
            } else {
                p.setTFlags(0);
            }

        }
        p.setTurnover(p.getTradingVolume().divide(new BigDecimal(10000)).setScale(2, BigDecimal.ROUND_HALF_UP));

        /** 判断是否需要刷新*/
        if (baseTask.isWorkTradeTime()) {
            p.setIsFlash(1);
        } else {
            p.setIsFlash(0);
        }
    }


    private BigDecimal getHistoryVol( TenXunStock p) {
        BigDecimal hisDayTradeVol=BigDecimal.ZERO;
        if(CollectionUtils.isEmpty(dates)){
             dates.addAll(companyStockMinutesMapper.queryDates());
        }
        /** 昨天 */
        int i = 2;
        int j = 0;
        String key_avg_volume=new StringBuffer("key_avg_volume").append("_").append(p.getStockCode()).append("_").append(HolidayCopy.getToday()).toString();
        Object object=redisUtil.get(key_avg_volume);
        if(null==object) {
            try{
                for (String date : dates) {
                    int size = dates.size() - i;
                    try {
                        date = dates.get(size);
                    } catch (Exception e) {
                        break;
                    }

                    //排除涨停的数据
                    Boolean isTrue = zhangTingBanService.zhangtingDatahis(p.getStockCode(), date);
                    isTrue=Boolean.FALSE;
                    if (!isTrue) {
                        BigDecimal yestoDayMaxVol = companyStockMinutesService.getMaxVol(date, p.getStockCode());
                        hisDayTradeVol = hisDayTradeVol.add(yestoDayMaxVol);
                        j++;
                    }
                    i++;
                    if (j == 4) {
                        if (p.getStockCode().startsWith("sh688")) {
                            hisDayTradeVol = hisDayTradeVol.divide(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_HALF_UP);
                        }
                        hisDayTradeVol = hisDayTradeVol.divide(new BigDecimal(5)).setScale(0, BigDecimal.ROUND_HALF_UP);
                        break;
                    }
                }
                redisUtil.set(key_avg_volume, hisDayTradeVol.toString());
            }catch (Exception e){
                log.error(">>>>>>>>> getHistoryVol error  code={} name={} dates={}",p.getStockCode(),p.getStockName(), JSONObject.toJSONString(dates));
            }
        }else {
            hisDayTradeVol = new BigDecimal(object.toString());
        }
        return hisDayTradeVol;
    }
}
